<?php



declare (strict_types=1);

namespace app\index\controller;

use app\mall\model\MallExpressCompany;
use app\mall\model\MallGoods;
use app\mall\model\MallGoodsCate;
use app\mall\model\MallGoodsMark;
use app\mall\model\MallUserActionCollect;
use app\mall\model\MallUserActionComment;
use app\mall\model\MallUsers;
use app\mall\service\ExpressService as ServiceExpressService;
use think\admin\Controller;
use think\admin\helper\QueryHelper;
use think\db\Query;

/**
 * 获取商品数据接口
 * @class Goods
 * @package plugin\wemall\controller\api
 */
class Goods extends Base
{


    /**
     * 获取商品列表
     * @return void
     */
    public function list()
    {
        $this->check_login();
        $param = request()->param();
        $this->cat_id = intval(input('cat_id', 0));
        $color_sort = intval(input('color_sort', 0));
        $where[] = ['status', '=', 1];
        $where[] = ['deleted', '=', 0];
        $sort = "sort desc,id desc";
        if(isset($param['cat_id']) && $param['cat_id'] > 0){
            $where[] = ['cates', '=', $param['cat_id']];
        }
         if(isset($param['color_sort']) && $param['color_sort'] > 0){
            $sort = "color_sort desc";
        }
        $this->cat_list = MallGoodsCate::mk()->where(['status' => 1, 'deleted' => 0])->order('sort desc,id desc')->select()->toArray();    
        $goods_list = MallGoods::where($where)->order($sort)->paginate([
            'list_rows'=> 10,
            'query' => request()->get(),
        ]);
        foreach ($goods_list as $key => $value) {
            $value->is_collect = MallUserActionCollect::where('unid', $this->uid)->where('gcode', $value->code)->count();
        }
        $this->goods_list = $goods_list;
        $this->param   = $param;
           // 计算分页信息
        $this->current_page = $goods_list->currentPage(); // 当前页
        $this->total_pages = $goods_list->lastPage(); // 总页数
        $this->prev_page = $this->current_page > 1 ? $this->current_page - 1 : null; // 上一页
        $this->next_page = $this->current_page < $this->total_pages ? $this->current_page + 1 : null; // 下一页
        $this->color_sort = $color_sort;
        return $this->fetch();
    }

    /**
     * 获取详情
     * @return void
     */
    public function detail($code)
    {
        $this->check_login();
        $this->goods_detail = MallGoods::with(['items','comments'=>function($query){
            $query->with('reply')->where('reply_id',0)->order('up_num desc,id desc');
        },'last_comments'=>function($query){
            $query->where('reply_id',0)->order('id desc')->limit(10);
        }])->where('code', $code)->append(['slider','specs'])->find();
    //    dump($this->goods_detail);die;
        $this->goods_detail->items_json = json_encode($this->goods_detail->items);
        $this->goods_detail->is_collect = MallUserActionCollect::where('unid', $this->uid)->where('gcode', $this->goods_detail->code)->count() ? true : false;
        return $this->fetch();
    }

    /**
     * 商品评价
     * @return void
     */
    public function comment(){
        $this->check_login();
        $data = $this->_vali([
            'unid.value' => $this->uid,
            'goods_id.require' => 'GOODS_EMPTY',
            'message.require' => 'COMMENT_CONTENT_EMPTY',
            'rating.require' => 'COMMENT_RATING_EMPTY',
            'ghash.value' => input('ghash', ''),
            'commentId.value' => input('commentId', 0),
        ]);
        if(!$goods = MallGoods::where('id', $data['goods_id'])->find()){
            $this->error('GOODS_NOT_FOUND');
        }
        $data['gcode'] = $goods->code;
        $data['rate']  = $data['rating'];
        $data['content'] = $data['message'];
        $user = MallUsers::where('id', $this->uid)->find();
        $data['avatar'] = $user->headimg;
        $data['user_name'] = $user->first_name.' '.$user->last_name;
        $data['reply_id'] = $data['commentId'];
        if(MallUserActionComment::create($data)){
            $this->success('SUCCESS');
        }else{
            $this->error('ERROR');
        };
    }

    /**
     * 评论点赞
     * @return void
     */
    public function comments_like(){
        $this->check_login();
        $data = $this->_vali([
            'unid.value' => $this->uid,
            'commentId.require' => 'COMMENT_EMPTY',
            'type.value' => input('type', 1),
        ]);
        if(!$comment = MallUserActionComment::where('id', $data['commentId'])->find()){
            $this->error('COMMENT_NOT_FOUND');
        }
        if($data['type'] == 1){
            $comment->up_num += 1;
        }else{
            $comment->down_num += 1;
        }
        if($comment->save()){
            $this->success('SUCCESS');
        }else{
            $this->error('ERROR');
        }
    }

    /**
     * 数据结果处理
     * @param array $data
     * @param array $result
     * @return void
     */
    protected function _get_page_filter(array &$data, array &$result)
    {
        $result['cnames'] = $this->cnames ?? null;
        $result['coupon'] = $this->coupon ?? null;
    }

    /**
     * 获取商品分类及标签
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function cate()
    {
        $this->success('获取分类成功', [
            'mark' => MallGoodsMark::items(),
            'cate' => MallGoodsCate::dtree(),
        ]);
    }

    /**
     * 获取商品评论
     * @return void
     */
    public function comments()
    {
        MallUserActionComment::mQuery(null, function (QueryHelper $query) {
            $query->with(['bindUser'])->equal('gcode')->order('id desc');
            $this->success('获取评论成功！', $query->page(intval(input('page', 1)), false, false, 30));
        });
    }

    /**
     * 商品评论处理
     * @param array $data
     * @return void
     */
    protected function _comments_page_filter(array &$data)
    {
        foreach ($data as &$item) {
            $item['user_phone'] = preg_replace('/(^\d{3})\d+(\d{3}$)/', '$1***$2', $item['user_phone']);
        }
    }

    /**
     * 获取物流配送区域
     * @return void
     * @throws \think\admin\Exception
     */
    public function region()
    {
        $this->success('获取配送区域', ServiceExpressService::region(3, 1));
    }

    /**
     * 获取快递公司数据
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function express()
    {
        $query = MallExpressCompany::mk()->where(['status' => 1, 'deleted' => 0]);
        $query->field(['name' => 'text', 'code' => 'value'])->order('sort desc,id desc');
        $this->success('获取快递公司', $query->select()->toArray());
    }


}